﻿        var count = 0;

        function findRowIdxForCheckbox(checkboxId) {
        
            var checkbox = document.getElementById(checkboxId);
            var cell = checkbox.parentNode;
            var row = cell.parentNode;
            var idx = row.rowIndex;
            
            return idx;
        }

        function swapRows(fromRow, toRow) {
        	wave.log("swapRows");        
        	var fromInputs = fromRow.getElementsByTagName("input");
        	var toInputs = toRow.getElementsByTagName("input");

        	var fromLabels = fromRow.getElementsByTagName("label");
        	var toLabels = toRow.getElementsByTagName("label");
        	
        	var checked = toInputs[0].checked;
        	toInputs[0].checked = fromInputs[0].checked;
        	fromInputs[0].checked = checked;

        	var value = toLabels[0].innerHTML;
        	toLabels[0].innerHTML = fromLabels[0].innerHTML
        	fromLabels[0].innerHTML = value;
        }

        function upRow(checkboxId) {
        	wave.log("upRow");
            var checklist = document.getElementById("checklist");
            var idx = findRowIdxForCheckbox(checkboxId);

            if (idx != 1) {
            	swapRows(checklist.rows[idx], checklist.rows[idx - 1]);
            }
        }

        function downRow(checkboxId) {
        	wave.log("downRow"); 
        	var checklist = document.getElementById("checklist");
            var idx = findRowIdxForCheckbox(checkboxId);

            if (idx < checklist.rows.length - 1) {
            	swapRows(checklist.rows[idx + 1], checklist.rows[idx]);
            }
        }
        
        function removeRow(checkboxId) {
            var checklist = document.getElementById("checklist");
            var idx = findRowIdxForCheckbox(checkboxId);
            checklist.deleteRow(idx);
            gadgets.window.adjustHeight();
           }

        function insertRow(idx, values) {
            if (values)
            	wave.log("insertRow(" + idx + ", " + values.length + ")");
            else
            	wave.log("insertRow(" + idx + ", null)");
        	var checklist = document.getElementById("checklist");
        	
        	checklist.insertRow(idx);
        	count = count + 1;
        	
        	var newRow = checklist.rows[idx];
        	var checkCell = newRow.insertCell(0);
        	var taskCell = newRow.insertCell(1);
        	var addCell = newRow.insertCell(2);

        	var checkboxId = "button" + count;

        	checkCell.setAttribute("style", "padding-top: 3px; padding-bottom: 3px; padding-left: 5px; padding-right: 5px;");
        	taskCell.setAttribute("style", "padding-top: 3px; padding-bottom: 3px; padding-left: 5px; padding-right: 5px;");
        	addCell.setAttribute("style", "padding-top: 3px; padding-bottom: 3px; padding-left: 5px; padding-right: 5px;");

        	if (wave.getMode() == wave.Mode.EDIT) {
        		checkCell.innerHTML = '<button id=' + '"' + checkboxId + '"' + ' type="button" onclick="removeRow(' + "'" + checkboxId + "'" + ')" /><img src="http://setresponsibility.googlecode.com/svn/trunk/delete.png" alt="-"/></button><input type="checkbox"/>';
        	}
        	else {
        		checkCell.innerHTML = '<input id=' + '"' + checkboxId + '"' + 'type="checkbox" onclick="checkChanged(' + "'" + checkboxId + "'" + ')"/>';
        	}
        	
        	if (wave.getMode() == wave.Mode.EDIT) {
        		if (values)
        			taskCell.innerHTML = '<label onclick="editTask(' + "'" + checkboxId + "'" + ')" style="text-decoration:underline; cursor:pointer;">' + values[1] + '</label>';
        		else
        			taskCell.innerHTML = '<label onclick="editTask(' + "'" + checkboxId + "'" + ')" style="text-decoration:underline; cursor:pointer;">Click on task to edit</label>';
        	}
        	else {
        		taskCell.innerHTML = values[1];
        	}

        	if (wave.getMode() == wave.Mode.EDIT) {
        		addCell.setAttribute("style", "padding-top: 3px; padding-bottom: 3px; padding-left: 5px; padding-right: 5px;");
        		addCell.innerHTML =
                '<button type="button" onclick="upRow(' + "'" + checkboxId + "'" + ')"><img src="http://setresponsibility.googlecode.com/svn/trunk/up.png" alt="^"/></button>' +
                '<button type="button" onclick="downRow(' + "'" + checkboxId + "'" + ')"><img src="http://setresponsibility.googlecode.com/svn/trunk/down.png" alt="v"/></button>' +
                '<button type="button" onclick="addRow(' + "'" + checkboxId + "'" + ')"><img src="http://setresponsibility.googlecode.com/svn/trunk/add.png" alt="+"/></button>';

        		var inputs = newRow.getElementsByTagName("input");
        		if (values[0] == 'true')
        			inputs[0].checked = true;
        		else
        			inputs[0].checked = false;
        	}
        	else {
        		var inputs = newRow.getElementsByTagName("input");
        		if (values[0] == 'true')
        			inputs[0].checked = true;
        		else
        			inputs[0].checked = false;
        	}
        }

        function checkChanged(checkboxId) {
        	wave.log("checkChanged: " + checkboxId);
        	var checklist = document.getElementById("checklist");
        	var idx = findRowIdxForCheckbox(checkboxId);
        	wave.log("-- row: " + idx);
        	var rowInputs = checklist.rows[idx].getElementsByTagName("input");
    		wave.log("-- state: " + rowInputs[0].checked);
    		stateValue = rowInputs[0].checked + "\n" + checklist.rows[idx].cells[1].innerHTML;
    		wave.log("-- " + idx + ": " + stateValue);
   			wave.getState().submitValue(idx, stateValue);
        }
        
        function editTask(checkboxId) {
        	var checklist = document.getElementById("checklist");
        	var idx = findRowIdxForCheckbox(checkboxId);
    		var rowLabels = checklist.rows[idx].getElementsByTagName("label");
    		var task = prompt("Enter a description of the task", rowLabels[0].innerHTML);
        	if (task)
        		rowLabels[0].innerHTML = task;
        }
        
        function addRow(checkboxId) {
        	var checklist = document.getElementById("checklist");
        	var idx = findRowIdxForCheckbox(checkboxId);
        	insertRow(idx + 1, null);
        	gadgets.window.adjustHeight();
        }

        function addFirstRow() {
        	var checklist = document.getElementById("checklist");
        	insertRow(1, null);
        	gadgets.window.adjustHeight();
        }
        
        function initializeFromState() {
        	var keys = wave.getState().getKeys();
        	wave.log("initializeFromState: [keys: " + keys.length + "]");
        	for (var idx = 1; idx <= keys.length; idx++) {
        		var state = wave.getState().get(idx.toString());
         		var values = state.split("\n");
        		insertRow(idx, values);
        	}
        	gadgets.window.adjustHeight();
        }

        function saveState() {
        	wave.log("saveState");
        	
        	var checklist = document.getElementById('checklist');
        	var listItems = checklist.rows.length - 1;
        	var stateItems = wave.getState().getKeys().length;
        	wave.log("[checklist: " + listItems + "][state: " + stateItems + "]");
        	
            var key = 1;
            for (; key < checklist.rows.length; key++) {
            	var rowInputs = checklist.rows[key].getElementsByTagName("input");
            	var rowLabels = checklist.rows[key].getElementsByTagName("label");
        		
        		var stateValue = null;
        		if (rowInputs.length == 1) {
        			stateValue = rowInputs[0].checked + "\n" + rowLabels[0].innerHTML;
        			wave.getState().submitValue(key, stateValue);
        		}
      		}

      		for (; key <= stateItems; key++)
      			wave.getState().submitValue(key, null); 
        }

        function resetTable() {
        	var checklist = document.getElementById('checklist');
        	wave.log("resetTable: [rows: " + checklist.rows.length + "][count: " + count + "]");
        	count = 0;
        	while (checklist.rows.length > 1)
        		checklist.deleteRow(1);
        	gadgets.window.adjustHeight();
        }
        
        function initializeForEditing() {
        	wave.log("initializeForEditing");
        	
            var addCell = document.getElementById("addCell0");
    		addCell.innerHTML =
                '<button type="button" onclick="addFirstRow()"><img src="http://setresponsibility.googlecode.com/svn/trunk/add.png" alt="+"/></button>';

    		resetTable();
    		initializeFromState();

    		gadgets.window.adjustHeight(500);    		
    	}

        function initializeForViewing() {
        	wave.log("initializeForViewing");
        	
            var addCell = document.getElementById("addCell0");
    		addCell.innerHTML = "";
                
       		saveState();
        	resetTable();
        	initializeFromState();
        }

        function stateUpdated() {
        	if (wave.getMode() == wave.Mode.VIEW) {
        		wave.log("stateUpdated");
        		resetTable();
        		initializeFromState();
        	}
        }

        function modeChanged() {
        	wave.log("modeChanged: " + wave.getMode()); 
        	if (wave.getMode() == wave.Mode.EDIT)
        		initializeForEditing();
        	else if (wave.getMode() == wave.Mode.VIEW)
        		initializeForViewing();
        }
        
        function init() {
          if (wave && wave.isInWaveContainer()) {
          	wave.setStateCallback(stateUpdated);
          	wave.setModeCallback(modeChanged)
          }
        }

        gadgets.util.registerOnLoadHandler(init);
        
       
